package com.longrise.android.by.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.ShareParams;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.login.TipsActivity;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.BaseFrameView;
import com.longrise.android.by.utils.BYUtil;
import com.longrise.android.ui.dialog.ShareDialog;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


/**
 * Created by sujizhong on 2017/1/8.
 * 保易智评
 */
public class XQPCActivity extends BaseActivity implements BaseFrameView.ReloadListener, View.OnClickListener {

    private static final String TAG = "XQPCActivity";

    private final int MSG_ON_START = 0;
    private final int MSG_PAGE_ERROR = 1;
    private final int MSG_ON_FINISH = 2;
    private final int MSG_ON_SHARE = 3;
    private final int MSG_ON_SHARE_VISIABLE = 4;
    private final int MSG_ON_LINKE = 5;

    private BaseFrameView mBf;
    private WebView mWebView;
    private WebSettings mWebSettings;

    private Toolbar mTitle;
    private RelativeLayout mRight;
    private ImageView mRightShare;
    private View mLoading;

    private boolean mIsError = false;

    private String title;
    private boolean mFlag;

    private String mUrl = "";

    private boolean mDestroy;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mDestroy) return;
            switch (msg.what) {
                case MSG_ON_START:
                    mBf.setVisibility(View.VISIBLE);
                    mBf.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
                    mWebView.setVisibility(View.GONE);
                    break;

                case MSG_PAGE_ERROR:
                    mBf.setVisibility(View.VISIBLE);
                    mBf.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
                    mWebView.setVisibility(View.GONE);
                    break;

                case MSG_ON_FINISH:
                    mBf.setVisibility(View.GONE);
                    mBf.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                    mWebView.setVisibility(View.VISIBLE);
                    break;

                case MSG_ON_SHARE:
                    try {
                        Share share = (Share) msg.obj;
                        showShare(share);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_ON_SHARE_VISIABLE:
                    try {
                        boolean isVisiable = (boolean) msg.obj;
                        mRight.setVisibility(isVisiable ? View.VISIBLE : View.GONE);
                        if (!mDestroy) {
                            showTips();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case MSG_ON_LINKE:
                    String url = (String) msg.obj;
                    linkTo(url);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_xqpc;
    }

    @Override
    public void initView() {
        init();
        if (checkNetwork()) {
            mHandler.sendEmptyMessage(MSG_ON_START);
            request();
        }
        mFlag = true;

        Tracker_Google.getInstance().addGoogleScreenName("保易智评");
    }

    private void init() {
        mWebView = (WebView) findViewById(R.id.activity_xqpc_webview);
        mBf = (BaseFrameView) findViewById(R.id.activity_xqpc_bv);
        mBf.setOnReloadListener(this);
        mLoading = findViewById(R.id.xupc_load);
        isLoading(false);
        setWebSetting();

        initTitle();

    }

    private void request() {
        int screenDp = 0;
        try {
            int topHeight = AppUtil.getStatusBar(this);
            int screenHeight = AppUtil.getScreenHeight();
            screenDp = AppUtil.px2dip(screenHeight - topHeight);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EntityBean entityBean = new EntityBean();
        entityBean.set("userid", UserInfor.getInstance().getUserid());
        entityBean.set("cardno", UserInfor.getInstance().getUsersfzh());
        entityBean.set("mobilephone", UserInfor.getInstance().getUserphone());
        entityBean.set("screenheight", screenDp - 45);
        entityBean.set("page", 2);
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", entityBean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BY_URL,
                "app_isauthorization", reqBean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    clientParse((EntityBean) result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mUrl = "";
                mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            }

            @Override
            public void onFinished(String key, String service) {
            }

        });
    }

    private void clientParse(EntityBean result) {
        if (result == null) {
            mUrl = "";
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return;
        }
        EntityBean bean = result.getBean("result");
        mUrl = bean.getString("href");
        if (isEmptyUrl()) {
            load();
        }
    }

    private boolean isEmptyUrl() {
        if (TextUtils.isEmpty(mUrl)) {
            mUrl = "";
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private void setWebSetting() {
        mWebSettings = mWebView.getSettings();

        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.setWebViewClient(mWebViewClient);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.addJavascriptInterface(new XQPCJSCallback(), "bb");
    }

    @Override
    public void onReload(View v) {
        if (checkNetwork()) {
            if (TextUtils.isEmpty(mUrl)) {
                mHandler.sendEmptyMessage(MSG_ON_START);
                request();
            } else {
                load();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_toolbar_share:
                mWebView.loadUrl("javascript:$_$.shareurl()");
                break;
        }
    }

    private class XQPCJSCallback {

        public XQPCJSCallback() {
        }

        @JavascriptInterface
        public void shareParams(String title, String content, String url, String iconUrl) {
            final ShareParams shareParams = new ShareParams();
            shareParams.mTitle = title;
            shareParams.mContent = content;
            shareParams.mUrl = url;
            shareParams.mHeadUrl = iconUrl;
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if(!isFinishing()){
                        ShareDialog shareDialog = new ShareDialog(XQPCActivity.this);
                        shareDialog.setShareParame(shareParams);
                        shareDialog.show();
                    }
                }
            });
        }

        @JavascriptInterface
        public void confirm(String url) {
            if (!TextUtils.isEmpty(url)) {
                Message msg = Message.obtain();
                msg.what = MSG_ON_LINKE;
                msg.obj = url;
                mHandler.sendMessage(msg);
            }
        }

        @JavascriptInterface
        public void loadFinish() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    isLoading(false);
                }
            });
        }
    }

    private void isLoading(boolean b) {
        mLoading.setVisibility(b ? View.VISIBLE : View.GONE);
    }

    private void linkTo(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri linkUrl = Uri.parse(url);
        intent.setData(linkUrl);
        startActivity(intent);
    }

    private class Share {
        private String mTitle;
        private String mContent;
        private String mUrl;
        private String mIconUrl;
    }

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!TextUtils.isEmpty(url)) {
                view.loadUrl(url);
            }
            isLoading(true);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (checkNetwork()) {
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            try {
                if (mIsError) {
                    mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
                } else {
                    mIsError = false;
                    mHandler.sendEmptyMessageDelayed(MSG_ON_FINISH, 500);
                }
                title = view.getTitle();
                Message msg = new Message();
                msg.obj = BYUtil.isVisiableShare(title);
                msg.what = MSG_ON_SHARE_VISIABLE;
                mHandler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mIsError = true;
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("error")) {
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    };

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle("保易网");
        mTitle.setNavigationIcon(R.drawable.ic_close_main);
        setSupportActionBar(mTitle);
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRight = (RelativeLayout) mTitle.findViewById(R.id.bb_toolbar_right_rl);
        mRight.setVisibility(View.INVISIBLE);
        mRightShare = (ImageView) mTitle.findViewById(R.id.iv_toolbar_share);
        mRightShare.setOnClickListener(this);
    }

    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
            return false;
        } else {
            return true;
        }
    }

    private void load() {
        if (!TextUtils.isEmpty(mUrl)) {
            mWebView.loadUrl(mUrl);
        } else {
            mHandler.sendEmptyMessage(MSG_PAGE_ERROR);
        }
    }

    private void release() {
        if (mWebView != null) {
            mWebView.removeAllViews();
        }
        if (mWebSettings != null) {
            mWebSettings.setJavaScriptEnabled(false);
        }
        mDestroy = true;
    }

    private void showShare(Share share) throws Exception {
        Tracker_Google.getInstance().addEvent("insurance-assessment", "share", "分享需求测评");
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
//        oks.setDialogMode();
        oks.disableSSOWhenAuthorize();
        oks.setTitle(share.mTitle);
        oks.setTitleUrl(share.mUrl);
        String content = "";
        if (share.mContent.length() > 50) {
            content = share.mContent.substring(0, 50).replace("&amp;", "&");
            oks.setText(content);
        } else {
            oks.setText(share.mContent.replace("&amp;", "&"));
        }
//        oks.setImagePath(FolderConstants.ICON_DIR + "/logoshare.jpg");
        oks.setImageUrl(share.mIconUrl);
        oks.setUrl(share.mUrl);
        oks.setSiteUrl(share.mUrl);
        oks.show(this);
    }

    /**
     * 新手提示
     */
    private void showTips() {
//        暂时不需要判断,每次进来都需要提示.
//        boolean b = Control.isbyShare();
//        if(!b){
//          return ;
//        }
        if (!mFlag) {
            return;
        }
        boolean e = "保易网需求分析测试".equals(title);
        if (e) {
            int[] loc1 = new int[2];
            mRightShare.getLocationInWindow(loc1);
            int width = mRightShare.getWidth();
            int height = mRightShare.getHeight();
            int h1 = AppUtil.dip2px(20);
            int com = AppUtil.dip2px(8);
            int[] loc = {loc1[0] - com, loc1[1] - h1 - com, loc1[0] + width + com, loc1[1] + height - h1 + com};
            Intent intent = new Intent(this, TipsActivity.class);
            intent.putExtra("type", TipsActivity.BYSHARE_TIPS);
            intent.putExtra("location", loc);
            startActivity(intent);
            mFlag = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }
}
